package com.wuzf.order.controller;

import org.springframework.cloud.client.discovery.DiscoveryClient;
import com.wuzf.common.entity.CommonResult;
import com.wuzf.common.entity.Payment;
import com.wuzf.order.config.LoadBalance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
public class OrderController {

    private static final String RPC_URL = "http://PROVIDER-PAYMENT";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalance loadBalance;


    @GetMapping("/order/payment/create")
    public Object create(Payment payment) {
        return restTemplate.postForEntity(RPC_URL + "/payment/create", payment, CommonResult.class);
    }


    @GetMapping("/order/payment/get/{id}")
    public Object get(@PathVariable long id) {
        return restTemplate.getForEntity(RPC_URL + "/payment/get/" + id, CommonResult.class);
    }


    /**
     * 自定义发现服务
     *
     * @param id
     * @return
     */
    @GetMapping("/order/discovery/get/{id}")
    public Object getDiscovery(@PathVariable long id) {
        List<ServiceInstance> instances = discoveryClient.getInstances("PROVIDER-PAYMENT");
        if (instances == null || instances.size() <= 0) {
            return null;
        }

        ServiceInstance instance = loadBalance.instance(instances);
        URI uri = instance.getUri();
        return restTemplate.getForEntity(uri + "/payment/get/" + id, CommonResult.class);
    }
}
